<template>
  <el-form
      ref="registryRefForm"
      :model="registryForm"
      :rules="rules"
      :label-position="labelPosition"
      :size="size"
      style="max-width: 350px"
      label-width="auto"
  >
    <el-form-item label="账号" prop="userName">
      <el-input type="text" v-model="registryForm.username" placeholder="请输入账号"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="registryForm.password" placeholder="请输入密码"/>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input type="password" v-model="registryForm.confirmPassword" placeholder="请再次输入密码"/>
    </el-form-item>
    <div style="width: 100%" class="myFlex-x">
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即注册</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.ts";

// 从父组件中获取传来的函数
const emit = defineEmits(["close-dialog"]);

let registryRefForm = ref();
const labelPosition = "right";
const size = ref('large');
let registryForm = ref({
  username: "",
  password: "",
  confirmPassword: ""
})
let rules = {
  username:[
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{5,12}$/,message: '账号必须是数字和字母组成，长度是5，12位',trigger: "blur"}
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{5,12}$/,message: '密码必须是数字和字母组成，长度是5，12',trigger: "blur"}
  ],
  confirmPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{5,12}$/,message: '密码必须是数字和字母组成，长度是5，12',trigger: "blur"},
    { validator: (rule, value, callback) => {
        if (value !== registryForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur'}
  ]
}
// 点击重置
function resetForm (){
  registryRefForm.value.resetFields()
}
// 点击注册
function submitForm(){
  registryRefForm.value.validate(async valid => {
    if (valid){
      // 发送注册请求，将用户输入的账号和密码发送给后端，将数据提交到数据库，然后后端响应数据给前端，这种请求是post请求
      request.post('/register', registryForm.value)
          .then(res => {
            let result = res.data;
            switch (result) {
              case 1:
                ElMessage.success("注册成功")
                emit("close-dialog")
                break;
              case 0:
                ElMessage.error("用户已存在")
                break;
              case -1:
                ElMessage.error("注册失败")
                break;
            }
          })
          .catch(err => {
            ElMessage.error("请求失败")
          })
    }else {
      ElMessage.error('注册失败')
    }
  })
}
</script>

<style scoped>

</style>